package com.iw.adoms.service;

import java.text.DecimalFormat;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.iw.adoms.dao.GoodsDao;
import com.iw.adoms.dao.QrBoxCodeDao;
import com.iw.adoms.dao.QrGoodsCodeDao;
import com.iw.adoms.entity.Goods;
import com.iw.adoms.entity.QrBoxCode;
import com.iw.adoms.entity.QrGoodsCode;
import com.iw.adoms.entity.StorageBatch;
import com.iw.adoms.entity.neum.FullStatus;
import com.iw.adoms.entity.neum.Status;
import com.iw.core.orm.hibernate.BaseDao;
import com.iw.core.orm.hibernate.BaseService;

@Service
@Transactional
public class StorageBatchService extends BaseService<StorageBatch> {

	@Autowired
	private GoodsDao goodsDao;

	@Autowired
	private QrGoodsCodeDao qrGoodsCodeDao;

	@Autowired
	private QrBoxCodeDao qrBoxCodeDao;

	@Override
	@Resource(name = "storageBatchDao")
	public void setBaseDao(BaseDao<StorageBatch> baseDao) {
		this.baseDao = baseDao;
	}

	public boolean inStorage(Integer batch, Model model, Goods goods, Integer boxid[], Integer qrid[]) throws Exception {

		if (qrid != null) {
			StorageBatch storageBatch = this.find(batch);
			// 初始化要入库的GOODS
			goods.setDepartment(storageBatch.getDepartment());
			goods.setMarchandise(storageBatch.getMarchandise());
			goods.setProduceDate(storageBatch.getProduceDate());

			// 新增货物
			for (Integer qid : qrid) {
				QrGoodsCode goodQr = qrGoodsCodeDao.find(qid);
				Goods g = goods.clone(goods) ;
				g.setQrCode(goodQr);
				g.setState(Status.WILL_SALE.getValue());
				goodsDao.save(g);
				// 更新货物二维码表中的状态
				goodQr.setState(Status.WILL_SALE.getValue());
				qrGoodsCodeDao.update(goodQr);
			}

			// 更新箱码的状态
			if (boxid != null) {
				for (Integer bid : boxid) {
					QrBoxCode box = qrBoxCodeDao.find(bid);
					box.setState(Status.HAS_IN.getValue());
					qrBoxCodeDao.update(box);
				}
			}
			// 更新完成的数量
			DecimalFormat df = new DecimalFormat("######0.00");
			storageBatch.setNumOfMarchandiseHasDone(storageBatch.getNumOfMarchandiseHasDone() + qrid.length); // 完成的
			storageBatch.setNumOfBoxHasDone(Double.valueOf(df.format(storageBatch.getNumOfMarchandiseHasDone() / storageBatch.getMarchandise().getNumOfBox().doubleValue())));
			// 更新批次的状态
			if (storageBatch.getNumOfMarchandise().equals(storageBatch.getNumOfMarchandiseHasDone())) {
				storageBatch.setState(FullStatus.ZDYWC.v());
			} else {
				storageBatch.setState(FullStatus.ZDRKZ.v());
			}
			this.baseDao.update(storageBatch);

			return true;
		}
		return false;

	}

}
